<template>
  <div class="role">
    <PageSearch
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />
    <PageContent
      :content-config="contentConfig"
      ref="contentRef"
      @new-click="handleNewClick"
      @edit-click="handleEditClick"
    >
      <template #name="scope">
        <span class="title">自定义：{{ scope.row[scope.prop] }}</span>
      </template>
    </PageContent>
    <PageModal
      ref="modalRef"
      :modal-config="modalConfigRef"
      :other-info="otherInfo"
    >
      <template #menulist>
        <el-tree
          ref="treeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
        />
      </template>
    </PageModal>
  </div>
</template>

<script setup lang="ts">
import PageSearch from '@/components/page-search/page-search.vue'
import PageContent from '@/components/page-content/page-content.vue'
import PageModal from '@/components/page-modal/page-modal.vue'
import { searchConfig } from './config/search-config'
import { contentConfig } from './config/content_config'
import { modalConfig } from './config/modal_config'
import { computed, nextTick, ref } from 'vue'
import { useMainStore } from '@/stores/main/main'
import { usePageContent } from '@/hooks/usePageContent'
import { usePageModal } from '@/hooks/usePageModal'
import { storeToRefs } from 'pinia'
import { ElTree } from 'element-plus'
import { mapMenuListToIds } from '@/utils/map-menus'

// 对modalConfig进行操作
const modalConfigRef = computed(() => {
  const mainStore = useMainStore()
  const roles = mainStore.entireDepartments.map((item) => {
    return { label: item.name, value: item.id }
  })
  modalConfig.formItems.forEach((item) => {
    if (item.prop === 'parentId') {
      item.options?.push(...roles)
    }
  })
  return modalConfig
})

// content、modal点击
const { contentRef, handleQueryClick, handleResetClick } = usePageContent()

// 新建数据
const { modalRef, handleNewClick, handleEditClick } = usePageModal(editCallback)

// 菜单数据
const mainStore = useMainStore()
const { menus } = storeToRefs(mainStore)
console.log({ ...menus })

const otherInfo = ref({})
const treeRef = ref<InstanceType<typeof ElTree>>()
function handleElTreeCheck(data1: any, data2: any) {
  const menulist = [...data2.checkedKeys, ...data2.halfCheckedKeys]
  otherInfo.value = { menulist }
}

function editCallback(data: any) {
  nextTick(() => {
    const menuIds = mapMenuListToIds(data.menulist)
    treeRef.value?.setCheckedKeys(menuIds)
  })
}
</script>

<style lang="scss" scoped>
.title {
  color: red;
}
</style>
